package com.example.contactapp;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

public class RegistryActivity extends AppCompatActivity {

    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_registry);


        //初始化DatebaseHelper
        dbHelper = new DatabaseHelper(this);
        Button registryButton = (Button) findViewById(R.id.registry_button);
        EditText usernameEdittext = (EditText) findViewById(R.id.username_edittext);
        EditText passwordEdittext = (EditText) findViewById(R.id.password_edittext);
        registryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取输入的用户名和密码
                String username = usernameEdittext.getText().toString().trim();
                String password = passwordEdittext.getText().toString().trim();

                // 检查输入是否为空
                if (username.isEmpty() || password.isEmpty()) {
                    Log.e("MainActivity", "Username or password cannot be empty");
                    return;
                }

                // 插入用户数据到数据库
                long userId = dbHelper.insertUser(username, password);

                if (userId != -1) {
                    Toast.makeText(RegistryActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                    goLogin(view);

                } else {
                    Toast.makeText(RegistryActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
                    usernameEdittext.setText("");
                    passwordEdittext.setText("");
                }
            }
        });
    }

    public void goLogin(View view){
        Intent intent = new Intent(RegistryActivity.this,LoginActivity.class);
        startActivity(intent);
    }
}